import datetime, itertools


from google.appengine.ext import db

from .. import cron, RESOLUTION
from .scheduled_item import ScheduledItem

def _execute_entry(entry, next_tick):
    net = item.next_execution_time
    while net < next_tick:
        # TODO: Can this go in some task-queue or something like that?
        entry.action.execute()
        net = cron.next(
            entry.action, 
            entry.next_execution_time)

        if net is None:
            entry.delete()
            # TODO: What about the action? Leave it in for history?
            return

    entry.next_execution_time = net

def execute_all(next_tick):
    # TODO: We can parallelize this, I imagine.
    for entry in ScheduleEntry.all():
        _execute_item(entry)

def add_item(action):
    now = datetime.datetime.now()
    entry = ScheduleEntry(
        action=action,
        next_execution_time=cron.next(item, now))
    
    entry.put()

    next_tick = now + datetime.timedelta(minutes=RESOLUTION)
        
    _execute_item(new_item, next_tick)
